package team.lourd.network.system.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import team.lourd.network.system.querydsl.ExtendedQuerydslJpaRepositoryFactoryBean;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "telecomEntityManagerFactory",   //EntityManagerFactory引用
        transactionManagerRef = "telecomTransactionManager",      //transactionManager引用
        basePackages = {"team.lourd.network.system.telecom.repository"},repositoryFactoryBeanClass = ExtendedQuerydslJpaRepositoryFactoryBean.class)

public class TelecomDataSourceConfig {

    @Resource(name = "telecomDataSource")
    private DataSource telecomDataSource;

    @Value("${spring.jpa.hibernate.secondary-dialect}")
    private String secondaryDialect;

    @Value("${spring.jpa.hibernate.naming.physical-strategy}")
    private String physicalStrategy;

    @Bean(name = "telecomEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("team.lourd.network.system.telecom.domain");
        Map<String, String> jpaProperties = new HashMap<String, String>();
        jpaProperties.put("hibernate.dialect", secondaryDialect);
        jpaProperties.put( "hibernate.physical_naming_strategy", physicalStrategy);
        factory.setJpaPropertyMap(jpaProperties);
        factory.setDataSource(telecomDataSource);
        return factory;
    }

    /**
     * 配置事务transactionManager
     * @param entityManagerFactory
     * @return PlatformTransactionManager
     */
    @Bean(name = "telecomTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }


}